import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView, Vibration, Text } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar } from 'react-native-elements';
import { primaryColor, executor, toast } from '../utils';
import { AssignFactoryQuery } from '../graphql';

const styles = StyleSheet.create({
  button: {
    marginTop: 16
  },
  icon: {
    marginRight: 16,
    color: primaryColor,
    fontSize: 16
  }
});

class AssignFactoryButton extends Component {
  state = {}
  onSubmit = () => {
    const { factories=[], selects } = this.props;
    if (!selects||selects.length===0) return toast(`Please select laundry bags`);

    Alert.alert(
      `Assign ${selects.length} bags to...`,
      selects.join('; '),
      [
        {text: 'Cancel'},
        ...factories.map(factory => {
          return {text: factory.name, onPress: () => {
            console.log(factory);
            executor(this.props.assignLaundryBags, factory)
              .then(({res}) => {
                if (res) {
                  toast(`Assign to ${factory.name} succeed`);
                  this.props.onSuccess();
                }
              });
            toast('Assigning...');
          }};
        })
      ],
      { cancelable: true }
    );
  }
  render() {
    const { processing } = this.state;

    return processing?<ActivityIndicator style={styles.spinner} color={primaryColor}/>:
      <TouchableOpacity onPress={this.onSubmit}>
        <Text style={styles.icon}>{this.props.chinese?'分厂':'Assign'}</Text>
      </TouchableOpacity>;
  }
}

export default compose(
  graphql(gql`
    query AssignFactoryButton {
      factories(limit:100) {
        id
        name
      }
    }
  `, {
    props: ({data:{factories}}) => {
      return {
        factories
      };
    }
  }),
  graphql(gql`
    mutation assignLaundryBags($laundryBags:[String]!,$factoryId:String!) {
      assignLaundryBags(laundryBags:$laundryBags,factoryId:$factoryId)
    }
  `, {
    name: 'assignLaundryBags',
    props: ({ownProps:{selects, date}, assignLaundryBags}) => {
      return {
        assignLaundryBags: (factory) => assignLaundryBags({
          variables: {
            laundryBags: selects,
            factoryId: factory.id
          },
          refetchQueries: [{
            query: AssignFactoryQuery,
            variables: { 
              date: date
            },
          }]
        })
      };
    }
  })
)(AssignFactoryButton);